import React from 'react';
import { fetchLeave } from '@/services/flowMine/apply';
import { Modal, Table, Button, message } from 'antd';

const columns = [
    {
        title: '请假类型',
        dataIndex: 'leaveName'
    },
    {
        title: '开始时间',
        dataIndex: 'startTime'
    },
    {
        title: '结束时间',
        dataIndex: 'endTime'
    },
    {
        title: '请假时长',
        dataIndex: 'leaveLong',
        render: time => <span>{`${time / 60} 小时`}</span>
    },
    {
        title: '请假状态',
        dataIndex: 'leaveStatusName',
        render: text => <span>{text.replace('请假-', '')}</span>
    }
];

const SelectLeave = ({ value = '', disabled, onChange }, ref) => {
    const [data, setData] = React.useState([]);
    const [visible, setVisible] = React.useState(false);
    const [loading, setLoading] = React.useState(true);

    const finalSelected = React.useMemo(() => data.find(item => item.applicationNo === value) || {}, [value, data]);

    const fetchData = async () => {
        setLoading(true);
        const response = await fetchLeave();
        if (response.code === 10000) {
            setData(response.data);
        }
        setLoading(false);
    };

    React.useEffect(() => {
        fetchData();
    }, []);

    React.useEffect(() => {
        /* 销假流程中的请假单号如果失效，做友好提示 */
        if (value !== '' && !loading && Object.keys(finalSelected).length === 0) {
            message.warn('此假期已失效，请重新选择！');
            onChange('');
            return;
        }
        onChange(value, finalSelected);
    }, [value, finalSelected, loading]);

    const handleChange = React.useCallback(
        _value => {
            onChange(_value[0]);
            setVisible(false);
        },
        [onChange]
    );

    const handleOpen = React.useCallback(() => {
        setVisible(true);
    }, [setVisible]);

    const handleCancel = React.useCallback(() => {
        setVisible(false);
    }, []);

    return (
        <div ref={ref}>
            <Button onClick={handleOpen} disabled={disabled}>
                选择
            </Button>
            {finalSelected.applicationNo && (
                <span style={{ paddingLeft: 16 }}>{`${finalSelected.leaveName} ${finalSelected.applicationNo}`}</span>
            )}
            <Modal
                title="请假记录"
                visible={visible}
                width="800px"
                onCancel={handleCancel}
                style={{ maxHeight: 100 }}
                footer={null}
            >
                <Table
                    rowKey="applicationNo"
                    loading={loading}
                    rowSelection={{ type: 'radio', selectedRowKeys: [value], onChange: handleChange }}
                    columns={columns}
                    dataSource={data}
                    pagination={false}
                />
            </Modal>
        </div>
    );
};

export default React.forwardRef(SelectLeave);
